import { useEffect, useRef } from 'react';
import { useAppSelector } from './redux';
import socketService from '../services/socketService';

// 自定义Hook：管理Socket.IO连接
export const useSocket = () => {
  const token = useAppSelector(state => state.auth.token);
  const isConnectedRef = useRef(socketService.getConnectionStatus());

  useEffect(() => {
    // 如果有token且当前未连接，则建立连接
    if (token && !isConnectedRef.current) {
      socketService.connect(token);
      isConnectedRef.current = true;
    }

    // 清理函数：组件卸载时断开连接
    return () => {
      if (isConnectedRef.current) {
        socketService.disconnect();
        isConnectedRef.current = false;
      }
    };
  }, [token]);

  // 返回socket服务实例以便在组件中使用
  return {
    isConnected: socketService.getConnectionStatus(),
    joinGame: socketService.joinGame.bind(socketService),
    leaveGame: socketService.leaveGame.bind(socketService),
    makeAction: socketService.makeAction.bind(socketService),
    startGame: socketService.startGame.bind(socketService),
  };
};